from app.errors import ParameterError
import openpyxl


class Excel():
    title = ['name', 'target', 'sourceIp']

    def __init__(self, wb_path, sheet_name):
        self.wb_path = wb_path
        self.sheet_name = sheet_name

    def data(self):
        try:
            wb = openpyxl.load_workbook(self.wb_path)
            sh = wb[self.sheet_name]
        except Exception as e:
            raise ParameterError(msg='请使用模板文件上传')
        rows = list(sh.rows)
        #先把sheet中每行数据保存为一个内嵌列表的列表
        case1 = []
        for row in rows:
            case2 = []
            for cell in row:
                if value := cell.value:
                    value = str(cell.value).strip().replace(' ', '').replace("\n", "")
                    # if value.startswith('#'):
                    #     case2 = []
                    #     break
                else:
                    value = ''
                case2.append(value)
            if set(case2) == {''} or not case2:
                continue
            case1.append(case2)
        #在把内嵌列表的列表转化为内嵌字典的列表，注意第一行数据是标题
        total = []
        # for a in case1[1:]:
        #     total.append(dict(zip(case1[0], a)))
        for a in case1[1:]:
            total.append(dict(zip(self.title, a)))
        return total
